package com.mango.community.controller.advice;

import com.mango.community.util.CommunityUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**  处理异常的全局配置类
 * @Author:  MangoCookieMilk
 * @Date:     2020/8/11 21:53
 * @ControllerAdvice(annotations = Controller.class)  代表他只会扫面有controller注解的bean 来用作统一的异常处理
 */
@ControllerAdvice(annotations = Controller.class)
public class ExceptionAdvice {

    private static final Logger logger = LoggerFactory.getLogger(ExceptionAdvice.class);

    /**@ExceptionHandler({Exception.class}) 表示所有的异常都会处理
     * 异常处理的方法
     * @param e
     * @param request
     * @param response
     */
    @ExceptionHandler({Exception.class})
    public void handleException(Exception e, HttpServletRequest request, HttpServletResponse response) throws IOException {
        //记录异常的概括信息到日志
        logger.error("服务器发声异常： "+e.getMessage());
        //记录异常的详细的栈信息
        //遍历异常的栈信息，记录
        for (StackTraceElement element: e.getStackTrace()){
            logger.error(element.toString());
        }
        //获取请求的方式
        String xRequestedWith = request.getHeader("x-requested-with");
        //判断请求的方式
        //"XMLHttpRequest".equals(xRequestedWith) 说明这是一个异步请求，返回json或者xml
        if("XMLHttpRequest".equals(xRequestedWith)){
            //返回给浏览器一个普通的字符串，需要前端手动的解析格式
            response.setContentType("application/plain;charset=utf-8");
            //将这个信息写出到浏览器
            PrintWriter writer = response.getWriter();
            writer.write(CommunityUtil.getJSONString(1,"服务器异常!"));
        }else {
            //否则就是返回错误页面，request.getContextPath() 获取项目的放回路径
            response.sendRedirect(request.getContextPath()+"/error");
        }
    }
}
